package com.powernode.controller;

import com.powernode.common.Constants;
import com.powernode.common.Result;
import com.powernode.domain.User;
import com.powernode.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 描述：文件上传
 */
@RequestMapping("upload")
@RestController
public class UploadController {
    private SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS");
    private Random random=new Random();

    private String rootPath="D:/upload/";

    @Resource
    private UserService userService;

    /**
     * 上传用户头像
     */
    @RequestMapping("uploadUserImg.action")
    public Result uploadUserImg(MultipartFile mf, HttpSession session){
        //得到文件老名字
        String oldName=mf.getOriginalFilename();
        //得到文件新名字
        String newName=createNewFileName(oldName);
        //保存图片
        try {
            mf.transferTo(new File(rootPath,newName));
            //把文件数据更新到数据库里面
            User sessionUser= (User) session.getAttribute(Constants.SESSION_USER_KEY);
            User user = userService.selectByPrimaryKey(sessionUser.getId());
            user.setImg(newName);
            //更新用户的图片数据
            this.userService.updateByPrimaryKeySelective(user);
            return new Result(200,"文件上传成功",0L,user.getImg());
        }catch (Exception e){
            e.printStackTrace();
            return new Result(-1,"文件上传失败");
        }
    }

    /**
     * 根据文件老名字生成文件的新名字
     * @param oldName
     * @return
     */
    private String createNewFileName(String oldName) {
        String end=oldName.substring(oldName.lastIndexOf("."));
        return sdf.format(new Date())+(random.nextInt(90000)+10000)+end;
    }
}
